package com.base.cn.platform.os.service.integralgood;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.dao.integralgood.IntegralCardVoucherDao;
import com.base.cn.platform.os.entity.integralgood.IntegralCardVoucher;
import com.base.cn.platform.os.entity.integralgood.IntegralCardVoucherExpand;
import com.base.cn.platform.os.entity.integralgood.IntegralExchangeRecord;
import com.base.cn.platform.os.entity.integralgood.IntegralVirtualGood;
import com.base.cn.platform.os.entity.op.giftcard.OpGiftCardCode;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 虚拟卡
 * @Author: Hello豆包
 * @Date: 2019/10/31 14:498
 */
@Service
public class IntegralCardVoucherBiz extends BaseBiz<IntegralCardVoucher, IntegralCardVoucherDao> {
    @Autowired
   private   IntegralVirtualGoodBiz integralVirtualGoodBiz;
        @Autowired
        private CusUserBiz cusUserBiz;
    /**
     * 保存数据
     * @param integralCardVouchers
     * @return
     */

    @Transactional(rollbackFor = IllegalArgumentException.class )
    public void virtualCardSave(List<IntegralCardVoucher> integralCardVouchers, String shopName){

        if(ObjectUtils.isNotEmpty(integralCardVouchers)){
            IntegralVirtualGood integralVirtualGood = new IntegralVirtualGood();
            integralVirtualGood.setName(shopName);
            integralVirtualGood.setInventory(integralCardVouchers.size());
            integralVirtualGoodBiz.save(integralVirtualGood);
            for(IntegralCardVoucher entity:integralCardVouchers){
                entity.setIntegralVirtualGoodId(integralVirtualGood.getId());
            }
            batchVirtualCardSave(integralCardVouchers);
        }
    }



    @Async
    public  void  batchVirtualCardSave(List<IntegralCardVoucher> integralCardVouchers){
        this.batchSave(integralCardVouchers);
    }



    /**
     *分页虚拟数据
     * @param page
     * @param integralVirtualGood
     * @return
     */
    public PageInfo<IntegralCardVoucher> findListPage(Pagination page, IntegralCardVoucherExpand integralVirtualGood){
        String s = whereSql(integralVirtualGood);
        PageInfo<IntegralCardVoucher> pageInfo = this.findPage(s, page, null);
        setUser(pageInfo.getList(),integralVirtualGood.isSetUserData());
        return pageInfo;
    }



    /**
     * 兑换虚拟卡
     * @param userId
     * @param integralVirtualGoodId
     * @return
     */
    public Map<String,Object> exchangeIntegralCardVoucher(BigDecimal userId,
                                                          BigDecimal integralVirtualGoodId,BigDecimal integralGoodId){

        List<IntegralCardVoucher> integralCardVouchers = this.queryIntegralCardVoucherList(integralVirtualGoodId, 1, null, 1);

        if (!ObjectUtils.isNotEmpty(integralCardVouchers)) {
            return ResultUtil.ERROR("商品库存不足");
        }
        integralCardVouchers.get(0).setUserId(userId);
        integralCardVouchers.get(0).setStatus(2);
        integralCardVouchers.get(0).setIntegralGoodId(integralGoodId);
        integralCardVouchers.get(0).setUseTime(new Date());
        this.updateBatch(integralCardVouchers);
        //修改商品库存
        IntegralVirtualGood byId = integralVirtualGoodBiz.findById(integralVirtualGoodId);
        IntegralVirtualGood integralVirtualGood = new IntegralVirtualGood();
        integralVirtualGood.setId(integralVirtualGoodId);
        integralVirtualGood.setInventory(byId.getInventory()-1);
        integralVirtualGood.setTheNumber(byId.getTheNumber()+1);
        integralVirtualGoodBiz.updateById(integralVirtualGood,null);
        return ResultUtil.SUCCESS("礼品卡赠送成功",integralCardVouchers.get(0).getId());
    }

    /**
     * 获取卡密
     * @param entity
     * @return
     */
    public  Map      geiInfoIntegralCardVoucher(IntegralCardVoucherExpand  entity){
        String s = whereSql(entity);
        IntegralCardVoucher one = findOne(s, null);

        if(ObjectUtils.isNotEmpty(one)){
          return   ResultUtil.SUCCESS("获取成功",one);
        }else{
         return    ResultUtil.ERROR("卡密失效了");
        }
    }




    /**
     * 特点条件搜索虚拟卡片
     * @param
     * @param status
     * @param userId
     * @param count
     * @return
     */
    public List<IntegralCardVoucher> queryIntegralCardVoucherList(BigDecimal integralVirtualGoodId,Integer status,BigDecimal userId,Integer count){
        StringBuilder whereSql = new StringBuilder();
        whereSql.append(" status =").append(status);
        if (DataUtil.idIsNotNull(integralVirtualGoodId)){
            whereSql.append(" and integralVirtualGoodId =").append(integralVirtualGoodId);
        }

        if (DataUtil.idIsNotNull(userId)){
            whereSql.append(" and userId=").append(userId);
        }else{
            whereSql.append(" and (userId is  null or userId =0)");
        }
        return this.find(whereSql.toString(),count,null);
    }


    /**
     * 设置兑换人
     * @param integralCardVoucher
     * @param isSetUser
     */
    public  void setUser(List<IntegralCardVoucher> integralCardVoucher, boolean isSetUser){

        if(isSetUser&&ObjectUtils.isNotEmpty(integralCardVoucher)){
            Set<String> shopUser = new HashSet<>();
            integralCardVoucher.stream().forEach(e->{
                if(  ObjectUtils.isNotEmpty(e.getUserId())){
                    shopUser.add(e.getUserId().toString());
                }
            });
            String sellList = shopUser.stream().collect(Collectors.joining(","));
            ArrayList<String> objects = new ArrayList<>();
            objects.add("id");
            objects.add("nickname");
            if(StringUtils.isNotEmpty(sellList)){
                List<CusUser> cusUsers = cusUserBiz.find(" id in (" + sellList + ")", null, objects);
                Map<BigDecimal, CusUser> shopDataListMap = cusUsers.stream().collect(Collectors.toMap(CusUser::getId, e -> e));
                for(IntegralCardVoucher entity:integralCardVoucher){
                    entity.setCusUser(shopDataListMap.get(entity.getUserId()));
                }
            }

        }
    }
    /**
     * 拼接sql
     * @param entity
     * @return
     */
    private   String  whereSql(IntegralCardVoucherExpand entity){
        StringBuilder sql = new StringBuilder(" 1=1 ");
        if (DataUtil.idIsNotNull(entity.getIntegralGoodId())){
            sql.append(" and integralGoodId =").append(entity.getIntegralGoodId());
        }
        if (DataUtil.idIsNotNull(entity.getId())){
            sql.append(" and id =").append(entity.getId());
        }
        if (DataUtil.idIsNotNull(entity.getUserId())){
            sql.append(" and userId=").append(entity.getUserId());
        }
        if (DataUtil.idIsNotNull(entity.getIntegralVirtualGoodId())){
            sql.append(" and integralVirtualGoodId=").append(entity.getIntegralVirtualGoodId());
        }
        if (ObjectUtils.isNotEmpty(entity.getStatus())){
            sql.append(" and status=").append(entity.getStatus());
        }
            if(ObjectUtils.isNotEmpty(entity.getStartTime())){
                sql.append(" and useTime>='"+ DateUtils.format(entity.getStartTime(), "yyyy-MM-dd HH:mm:ss")).append("'");
            }
         if (ObjectUtils.isNotEmpty(entity.getEndTime())){
             sql.append(" and useTime<='"+ DateUtils.format(entity.getEndTime(), "yyyy-MM-dd HH:mm:ss")).append("'");
             }
        return  sql.toString();
    }
}
